package com.falcon.mojo;

import com.falcon.util.PathUtil;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;

import java.io.File;
import java.io.IOException;

/** 合并源码文件 */
@Mojo(name = "source-merge", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
public class SourceMergeMojo extends AbsMojo {

    public void execute() throws MojoExecutionException, MojoFailureException {
        String mergeModule = this.project.getBasedir().getAbsolutePath();

        // 获取要合并的模块列表
        File[] modules = enableIncludeModules ? includeModules : getSubModules();

        for (File module : modules) {
            getLog().info("[源码合并] 合并目录:" + module.getName() + PathUtil.JAVA_SOURCE_DIR );
            mergeDirectory(PathUtil.getJavaSourceDir(module.getAbsolutePath()), PathUtil.getJavaSourceDir(mergeModule));

            getLog().info("[源码合并] 合并目录:" + module.getName() + PathUtil.RESOURCES_DIR );
            mergeDirectory(PathUtil.getResourcesDir(module.getAbsolutePath()), PathUtil.getResourcesDir(mergeModule));

            getLog().info("[源码合并] 合并目录:" + module.getName() + PathUtil.JAVA_SOURCE_DIR );
            mergeDirectory(PathUtil.getTestJavaSourceDir(module.getAbsolutePath()), PathUtil.getTestJavaSourceDir(mergeModule));

            getLog().info("[源码合并] 合并目录:" + module.getName() + PathUtil.TEST_JAVA_SOURCE_DIR );
            mergeDirectory(PathUtil.getTestResourcesDir(module.getAbsolutePath()), PathUtil.getTestResourcesDir(mergeModule));
        }
    }

    /** 合并 */
    private void mergeDirectory(String sourceDirectoryPath, String targetDirectoryPath) {
        File sourceDirectory = new File(sourceDirectoryPath);
        if (!sourceDirectory.exists() || !sourceDirectory.isDirectory()) {
            return;
        }

        File targetDirectory = new File(targetDirectoryPath);
        if (!targetDirectory.exists()) {
            targetDirectory.mkdirs();
        }

        try {
            FileUtils.copyDirectory(sourceDirectory, targetDirectory);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
